思路:在原本直接回溯版本的基础上,走下一步的时候考虑下一步的下一步可行解的数量,按可行解的数量从小到大的顺序选择下一步。优化出来的效率高很多,再次感受到算法的魅力。
/*输入n*n的棋盘,输出从给定位置出发的马踏棋盘的路径*/
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define debug cout<<"debug___________"<<endl
using namespace std;
const int maxn=100;
int chess[maxn][maxn];
int sx,sy;
int n;
int dirx[]={-2,-1,1,2,2,1,-1,-2};
int diry[]={1,2,2,1,-1,-2,-2,-1};
struct Step{
int dir,cnt;
};
bool cmp(Step a,Step b){
return a.cnt<b.cnt;
}
bool judge(int x,int y){
return (x>=1&&x<=n)&&(y>=1&&y<=n);
}
bool dfs(int x,int y,int depth){
if(depth==n*n){debug;debug;
return true;
}
Step ok[8];
memset(ok,0,sizeof(ok));
for(int i=0;i<8;i++){
int next_x=x+dirx[i];
int next_y=y+diry[i];
if(!judge(next_x,next_y)||chess[next_x][next_y]) continue;
if(depth==n*n-1){
chess[next_x][next_y]=depth+1;
return true;
}
for(int j=0;j<8;j++){
int next_next_x=next_x+dirx[j];
int next_next_y=next_y+diry[j];
if(!chess[next_next_x][next_next_y]&&judge(next_next_x,next_next_y)){
ok[i].cnt++;
ok[i].dir=i;
}
}
}
int temp_x,temp_y;
sort(ok,ok+8,cmp);
int i;
for(i=0;i<8;i++){
if(ok[i].cnt){
temp_x=x+dirx[ok[i].dir];
temp_y=y+diry[ok[i].dir];
if(!chess[temp_x][temp_y]){
chess[temp_x][temp_y]=depth+1;
if(dfs(temp_x,temp_y,depth+1)) break;
chess[temp_x][temp_y]=0;
}
}
}
if(i==8) return false;
return true;
}
int main(){
while(scanf("%d",&n)!=EOF){
if(n<6){
printf("erro\n");
continue;
}
memset(chess,0,sizeof(chess));
scanf("%d%d",&sx,&sy);
chess[sx][sy]=1;
if(dfs(sx,sy,1)){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
printf("%3d%c",chess[i][j],j==n?'\n':' ');
}
}
else
printf("No solution\n");
}
return 0;
}